﻿<template>
	<div class="deviceInfo-container">
		<el-dialog v-model="isShowDialog" :width="800" draggable="" :close-on-click-modal="false">
			<template #header>
				<div style="color: #fff">
					<!--<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Edit /> </el-icon>-->
					<span>{{ props.title }}</span>
				</div>
			</template>
			<el-form :model="ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
				<el-row :gutter="35">
					<el-form-item v-show="false">
						<el-input v-model="ruleForm.id" />
					</el-form-item>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="设备名称" prop="deviceName">
							<el-input v-model="ruleForm.deviceName" placeholder="请输入设备名称" maxlength="100"
								show-word-limit clearable />

						</el-form-item>

					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="设备编号" prop="deviceNo">
							<el-input v-model="ruleForm.deviceNo" placeholder="请输入设备编号" maxlength="50" show-word-limit
								clearable />

						</el-form-item>

					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="描述" prop="description">
							<el-input v-model="ruleForm.description" placeholder="请输入描述" maxlength="500" show-word-limit
								clearable />

						</el-form-item>

					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="地址" prop="address">
							<el-input v-model="ruleForm.address" placeholder="请输入地址" maxlength="200" show-word-limit
								clearable />

						</el-form-item>

					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="位置" prop="position">
							<el-input v-model="ruleForm.position" placeholder="请输入位置" maxlength="100" show-word-limit
								clearable />

						</el-form-item>

					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="位置类型" prop="devicePositionType">
							<el-select clearable v-model="ruleForm.devicePositionType" placeholder="请选择位置类型">
								<el-option v-for="(item, index) in dl('DevicePositionType')" :key="index"
									:value="Number(item.value)"
									:label="`${item.name} (${item.code}) [${item.value}]`"></el-option>

							</el-select>

						</el-form-item>

					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="设备网关ID" prop="deviceGateWayId">
							<el-select clearable filterable v-model="ruleForm.deviceGateWayId" placeholder="请选择设备网关ID">
								<el-option v-for="(item, index) in deviceGateWayDeviceGateWayIdDropdownList"
									:key="index" :value="item.value" :label="item.label" />
							</el-select>
						</el-form-item>
					</el-col>
					
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="直属机构Id" prop="orgId">
							<el-cascader :options="sysOrgTreeData"
								:props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'name' }"
								placeholder="请选择直属机构Id" clearable="" class="w100" v-model="ruleForm.orgId">
								<template #default="{ node, data }">
									<span>{{ data.name }}</span>
									<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
								</template>
							</el-cascader>

						</el-form-item>

					</el-col>

				</el-row>
			</el-form>
			<el-card>
				<template #header>
					<div class="card-header">
						<span>从机配置</span>
						<span v-if="deviceTemplateName">（当前模板：{{ deviceTemplateName }}）</span>
						<el-button type="primary" @click="openTemplateDialog">选择设备模板</el-button>
					</div>
				</template>
				<el-form>
					<el-row justify="space-evenly">
						<el-col v-for="(slave, index) in ruleForm.deviceRelSlaves" :key="index" :span="24" class="mb20">
							<el-card shadow="hover">
								<el-row :gutter="1" justify="space-evenly">
									<el-col :span="3">
										{{ slave.deviceSlaveTemplate.slaveName + ':' }}
									</el-col>
									<el-col :span="8">
										<el-form-item label="串口序号:">
											<el-input v-model="slave.comIdx" placeholder="请输入串口序号" />
										</el-form-item>
									</el-col>
									<el-col :span="8">
										<el-form-item label="从机地址:">
											<el-input v-model="slave.slaveAddr" placeholder="请输入从机地址" />
										</el-form-item>
									</el-col>

								</el-row>
							</el-card>


						</el-col>
					</el-row>
				</el-form>

			</el-card>
			<el-dialog v-model="isTemplateDialogVisible" title="选择设备模板" width="30%">
				<el-select clearable filterable v-model="selectedTemplateId" placeholder="请选择设备模板ID">
					<el-option v-for="(item, index) in deviceTemplateInfoDeviceTemplateInfoIdDropdownList" :key="index"
						:value="item.value" :label="item.label" />
				</el-select>

				<template #footer>
					<span class="dialog-footer">
						<el-button @click="isTemplateDialogVisible = false">取 消</el-button>
						<el-button type="primary" @click="confirmTemplateSelection">确 定</el-button>
					</span>
				</template>
			</el-dialog>


			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel">取 消</el-button>
					<el-button type="primary" @click="submit">确 定</el-button>
				</span>
			</template>

		</el-dialog>

	</div>
</template>
<style lang="scss" scoped>
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}

.card-header {
	display: flex;
	align-items: center;
	gap: 16px;
	/* 设置元素之间的间距 */
}
</style>
<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElLoading, ElMessageBox } from "element-plus";
import type { FormRules } from "element-plus";
import { getDictDataItem as di, getDictDataList as dl } from '/@/utils/dict-utils';
import { getDictLabelByVal as dv } from '/@/utils/dict-utils';
import { formatDate } from '/@/utils/formatTime';
import { addDeviceInfo, updateDeviceInfo, detailDeviceInfo, updateDeviceInfoSlaves } from "/@/api/Device/DeviceInfo/deviceInfo";
import { getDeviceGateWayDeviceGateWayIdDropdown } from '/@/api/Device/DeviceInfo/deviceInfo';
import { getDeviceTemplateInfoDeviceTemplateInfoIdDropdown } from '/@/api/Device/DeviceInfo/deviceInfo';
import { getSysOrgTree } from '/@/api/Device/DeviceInfo/deviceInfo';
import { pageDeviceSlaveTemplate } from '/@/api/Device/Template/deviceSlaveTemplate';
import { pageDeviceRelSlave } from '/@/api/Device/DeviceRelSlave/deviceRelSlave';
import { getAPI } from '/@/utils/axios-utils';
import { SysEnumApi } from '/@/api-services/api';

//父级传递来的参数
var props = defineProps({
	title: {
		type: String,
		default: "",
	},
});
//父级传递来的函数，用于回调
const emit = defineEmits(["reloadTable"]);
const ruleFormRef = ref();
const isShowDialog = ref(false);
const ruleForm = ref<any>({});
const isTemplateDialogVisible = ref(false);
const selectedTemplateId = ref(null);

//v-loading
const loading = ref(false);

//自行添加其他规则
const rules = ref<FormRules>({
	deviceName: [{ required: true, message: '请输入设备名称！', trigger: 'blur', },],
	deviceNo: [{ required: true, message: '请输入设备编号！', trigger: 'blur', },],
	description: [{ required: true, message: '请输入描述！', trigger: 'blur', },],
	address: [{ required: true, message: '请输入地址！', trigger: 'blur', },],
	position: [{ required: true, message: '请输入位置！', trigger: 'blur', },],
	orgId: [{ required: true, message: '请选择直属机构Id！', trigger: 'change', },],
});

const deviceTemplateName = ref<string | null>(null);

const fetchDeviceTemplateName = async (templateId: number) => {
	try {
		const list = await getDeviceTemplateInfoDeviceTemplateInfoIdDropdown();
		const template = list.data.result.find((item: any) => item.value === templateId);
		deviceTemplateName.value = template ? template.label : null;
	} catch (error) {
		ElMessage.error('获取设备模板名称失败:' + error);
	}
};

// 页面加载时
onMounted(() => {

});

// 打开弹窗
const openDialog = async (row: any) => {
	// ruleForm.value = JSON.parse(JSON.stringify(row));
	// 改用detail获取最新数据来编辑
	await refreshDeviceGateWayId();
	try {
		deviceTemplateName.value = null;
		let rowData = JSON.parse(JSON.stringify(row));
		if (rowData.id)
			ruleForm.value = (await detailDeviceInfo(rowData.id)).data.result;
		else
			ruleForm.value = rowData;

		if (ruleForm.value.deviceTemplateInfoId) {
			await fetchDeviceTemplateName(ruleForm.value.deviceTemplateInfoId);
		}
		isShowDialog.value = true;
	} catch (error) {
		ElMessage.error('获取设备信息失败:' + error);
	}

};

// 关闭弹窗
const closeDialog = () => {
	emit("reloadTable");
	isShowDialog.value = false;
};

// 取消
const cancel = () => {
	emit("reloadTable");
	isShowDialog.value = false;
};

// 提交
const submit = async () => {
	// 这里可以调用API提交数据
	try {
		ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
			if (isValid) {
				let values = ruleForm.value;
				values.isSlaveUpdate = true;
				if (ruleForm.value.id == undefined || ruleForm.value.id == null || ruleForm.value.id == "" || ruleForm.value.id == 0) {
					await addDeviceInfo(values);
				} else {
					await updateDeviceInfo(values);
				}
				closeDialog();
			} else {
				ElMessage({
					message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
					type: "error",
				});
			}
		});
	} catch (error) {
		ElMessage.error('提交失败:' + error);
	}

};

// 获取设备模板下的所有从机
// 打开选择设备模板对话框
const openTemplateDialog = async () => {
	try {
		try {
			ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
				if (isValid) {
					let values = ruleForm.value;
					if (ruleForm.value.id == undefined || ruleForm.value.id == null || ruleForm.value.id == "" || ruleForm.value.id == 0) {
						var re = await addDeviceInfo(values);
						ruleForm.value.id = re.data.result;

					} else {
						await updateDeviceInfo(values);
					}
					await getDeviceTemplateInfoDeviceTemplateInfoIdDropdownList();
					isTemplateDialogVisible.value = true; // 打开选择设备模板对话框
				} else {
					ElMessage({
						message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
						type: "error",
					});
				}
			});
		} catch (error) {
			ElMessage.error('提交失败:' + error);
		}

	} catch (error) {
		ElMessage.error('操作失败:' + error);
	}
};

// 确认选择设备模板
const confirmTemplateSelection = async () => {
	isTemplateDialogVisible.value = false;
	ElMessageBox.confirm('是否要更新设备模板？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		try {
			let values = ruleForm.value;
			values.DeviceTemplateInfoId = selectedTemplateId.value;
			await updateDeviceInfoSlaves(values);
			ElMessage.success('设备模板更新成功');
			// 更新设备信息
			ruleForm.value = (await detailDeviceInfo(ruleForm.value.id)).data.result;
		} catch (error) {
			ElMessage.error('更新设备模板失败:' + error);
		}
	}).catch(() => {
		ElMessage.info('已取消更新设备模板');
	});
};
// 获取设备模板从机
const fetchDeviceTemplates = async () => {
	const loading = ElLoading.service({
		lock: true,
		text: '加载中...',
		spinner: 'el-icon-loading',

	});
	try {

		ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
			if (isValid) {
				let values = ruleForm.value;
				values.isSlaveUpdate = false;
				if (ruleForm.value.id == undefined || ruleForm.value.id == null || ruleForm.value.id == "" || ruleForm.value.id == 0) {
					var re = await addDeviceInfo(values);
					console.log(re)
					ruleForm.value = (await detailDeviceInfo(re.data.result)).data.result;
				} else {
					// 增加loading

					await updateDeviceInfo(values);
					ruleForm.value = (await detailDeviceInfo(ruleForm.value.id)).data.result;
				}

			} else {
				ElMessage({
					message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
					type: "error",
				});
			}
		});

	} catch (error) {
		ElMessage.error('获取设备模板失败');
	} finally {
		loading.close();
	}
};

const deviceGateWayDeviceGateWayIdDropdownList = ref<any>([]);
const getDeviceGateWayDeviceGateWayIdDropdownList = async () => {
	try {
		let list = await getDeviceGateWayDeviceGateWayIdDropdown();
		deviceGateWayDeviceGateWayIdDropdownList.value = list.data.result ?? [];
	} catch (error) {
		ElMessage.error('获取设备网关ID失败:' + error);
	}

};
getDeviceGateWayDeviceGateWayIdDropdownList();

const refreshDeviceGateWayId = async () => {
	try {
		await getDeviceGateWayDeviceGateWayIdDropdownList();
	} catch (error) {
		ElMessage.error('刷新设备网关ID失败:' + error);
	}
};

const deviceTemplateInfoDeviceTemplateInfoIdDropdownList = ref<any>([]);
const getDeviceTemplateInfoDeviceTemplateInfoIdDropdownList = async () => {
	try {
		let list = await getDeviceTemplateInfoDeviceTemplateInfoIdDropdown();
		deviceTemplateInfoDeviceTemplateInfoIdDropdownList.value = list.data.result ?? [];
	} catch (error) {
		ElMessage.error('获取设备模板ID失败:' + error);
	}

};
getDeviceTemplateInfoDeviceTemplateInfoIdDropdownList();


const sysOrgTreeData = ref<any>([]);
const getSysOrgTreeData = async () => {
	let list = await getSysOrgTree();
	sysOrgTreeData.value = list.data.result ?? [];
};
getSysOrgTreeData();



// 提交从机通讯信息
const submitSlaveCommunications = async () => {
	try {
		// 这里可以调用API提交从机通讯信息
		// await submitSlaveCommunicationsAPI(deviceTemplateSlaves.value);
		ElMessage.success('从机通讯信息提交成功');
	} catch (error) {
		ElMessage.error('提交从机通讯信息失败');
	}
};



//将属性或者函数暴露给父组件
defineExpose({ openDialog });
</script>
